package com.roads.project.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import com.roads.common.constant.UserConstants;
import com.roads.common.core.domain.chart.BaseChartModel;
import com.roads.common.utils.SecurityUtils;
import com.roads.common.utils.StringUtils;
import com.roads.project.domain.ProBoq;
import com.roads.project.domain.ProInstitution;
import com.roads.project.domain.ProPaymentItems;
import com.roads.project.service.IProBoqService;
import com.roads.project.service.IProInstitutionService;
import com.roads.project.service.IProPaymentItemsService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.roads.common.annotation.Log;
import com.roads.common.core.controller.BaseController;
import com.roads.common.core.domain.AjaxResult;
import com.roads.common.enums.BusinessType;
import com.roads.project.domain.ProProject;
import com.roads.project.service.IProProjectService;
import com.roads.common.utils.poi.ExcelUtils;
import com.roads.common.core.page.TableDataInfo;

/**
 * 建设项目Controller
 *
 * @author nhp
 * @date 2021-11-15
 */
@RestController
@RequestMapping("/project/project")
public class ProProjectController extends BaseController {

    @Autowired
    private IProProjectService proProjectService;

    @Autowired
    private IProInstitutionService proInstitutionService;

    @Autowired
    private IProPaymentItemsService paymentItemsService;

    @Autowired
    private IProBoqService boqService;

    /**
     * 查询建设项目列表
     */
    @PreAuthorize("@ss.hasPermi('project:project:list')")
    @GetMapping("/list")
    public TableDataInfo list(ProProject proProject) {
        startPage();
        proProject.setCreateBy(getUsername());
        List<ProProject> list;
        if (SecurityUtils.isAdmin(getUserId())) {
            list = proProjectService.selectProProjectListAll(proProject);
        } else {
            list = proProjectService.selectProProjectList(proProject);
        }
        return getDataTable(list);
    }

    /**
     * 查询项目下拉框，admin查询全部
     * @return
     */
    @GetMapping("/selectProjectList")
    public AjaxResult selectProjectList() {
        ProProject proProject = new ProProject();
        proProject.setCreateBy(getUsername());
        List<ProProject> list;
        if (SecurityUtils.isAdmin(getUserId())) {
            list = proProjectService.selectProProjectListAll(proProject);
        } else {
            list = proProjectService.selectProProjectList(proProject);
        }
        AjaxResult ajax = new AjaxResult();
        ajax.put("projects", list);
        return ajax;
    }

    /**
     * 导出建设项目列表
     */
    @PreAuthorize("@ss.hasPermi('project:project:export')")
    @Log(title = "建设项目", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(ProProject proProject) {
        List<ProProject> list = proProjectService.selectProProjectList(proProject);
        ExcelUtils<ProProject> util = new ExcelUtils<ProProject>(ProProject.class);
        return util.exportExcel(list, "建设项目数据");
    }

    /**
     * 获取建设项目详细信息
     */
    @PreAuthorize("@ss.hasPermi('project:project:query')")
    @GetMapping(value = "/{projectId}")
    public AjaxResult getInfo(@PathVariable("projectId") Integer projectId) {
        return AjaxResult.success(proProjectService.selectProProjectByProjectId(projectId));
    }

    /**
     * 根据项目编号获取项目信息
     *
     * @param projectCode 项目编号
     * @return 项目信息
     */
    @PostMapping("/getProjectByCode")
    public AjaxResult getProjectByCode(String projectCode) {
        return AjaxResult.success(proProjectService.getProjectByCode(projectCode));
    }

    /**
     * 新增建设项目
     */
    @PreAuthorize("@ss.hasPermi('project:project:add')")
    @Log(title = "建设项目", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ProProject proProject) {
        if (UserConstants.NOT_UNIQUE.equals(proProjectService.checkProjectCodeUnique(proProject))) {
            return AjaxResult.error("新增建设项目'" + proProject.getProjectCode() + "'失败，项目编号已存在");
        }
        proProject.setCreateBy(getUsername());
        return toAjax(proProjectService.insertProProject(proProject));
    }

    /**
     * 修改建设项目
     */
    @PreAuthorize("@ss.hasPermi('project:project:edit')")
    @Log(title = "建设项目", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ProProject proProject) {
        if (UserConstants.NOT_UNIQUE.equals(proProjectService.checkProjectCodeUnique(proProject))) {
            return AjaxResult.error("修改建设项目'" + proProject.getProjectCode() + "'失败，项目编号已存在");
        }
        proProject.setUpdateBy(getUsername());
        return toAjax(proProjectService.updateProProject(proProject));
    }

    /**
     * 删除建设项目
     */
    @PreAuthorize("@ss.hasPermi('project:project:remove')")
    @Log(title = "建设项目", businessType = BusinessType.DELETE)
    @DeleteMapping("/{projectIds}")
    public AjaxResult remove(@PathVariable Integer[] projectIds) {
        // 项目删除校验
        for (int i = 0; i < projectIds.length; i++) {
            int count = proInstitutionService.countByProjectId(projectIds[i]);
            if (count > 0) {
                return error("项目下已存在机构，不能进行删除，若要删除，请先删除机构");
            }
        }
        return toAjax(proProjectService.deleteProProjectByProjectIds(projectIds));
    }

    /**
     * 获取项目百章金额饼状图数据
     *
     * @param projectId 项目ID
     * @return 结果
     */
    @RequestMapping("/getProjectHundredChaptersTotalChartPie/{projectId}")
    public AjaxResult getProjectHundredChaptersTotalChartPie(@PathVariable("projectId") Integer projectId) {
        AjaxResult ajaxResult = new AjaxResult();
        String userName = SecurityUtils.getUsername();
        boolean isAdmin = SecurityUtils.isAdmin(SecurityUtils.getUserId());
        ProPaymentItems search = new ProPaymentItems();
        search.setProjectId(projectId);
        search.setComputeMode(1);
        search.setItemStatus("0");
        List<ProPaymentItems> items = paymentItemsService.selectModelList(search);
        List<ProInstitution> bids;
        if (isAdmin) {
            bids = proInstitutionService.selectBidListByProjectId(projectId);
        } else {
            bids = proInstitutionService.selectBidListByUserAndProjectId(projectId, userName);
        }
        List<BaseChartModel> data = new ArrayList<>();
        List<String> legend = new ArrayList<>();
        for (ProPaymentItems item : items) {
            BaseChartModel chart = new BaseChartModel();
            chart.setName(item.getItemCode() + "章");
            legend.add(item.getItemCode() + "章");
            BigDecimal total = BigDecimal.valueOf(0);
            for (ProInstitution bid : bids) {
                String institutionCode = bid.getInnerCode();
                ProBoq boq = boqService.selectProBoqByCode(institutionCode, item.getItemCode());
                if (StringUtils.isNotNull(boq)) {
                    BigDecimal boqTotal = boq.getTotal() == null ? BigDecimal.valueOf(0) : boq.getTotal();
                    total = total.add(boqTotal);
                }
            }
            total = total.divide(BigDecimal.valueOf(10000),0, BigDecimal.ROUND_HALF_UP);
            chart.setValue(total.intValue());
            data.add(chart);
        }
        ajaxResult.put("legend", legend);
        ajaxResult.put("data", data);
        return ajaxResult;
    }

}
